package com.hmall.search;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;

/**
 *
 */
@SpringBootTest
@Slf4j
public class InsertAll {

    @Autowired
    private ItemClient itemClient;

    private RestHighLevelClient client;

    /**
     * 批量导入
     */
    @Test
    public void test1() throws IOException {

        Integer page = 1;
        IndexRequest request = new IndexRequest("hmall");
        while (true) {
            PageDTO pageDTO = itemClient.page(page, 25);
            BulkRequest bulkRequest = new BulkRequest();
            List<Item> list = pageDTO.getList();

            if (list.size() == 0) {
                break;
            }
            for (Item item : list) {
                ItemDoc itemDoc = new ItemDoc(item);
                String json = JSON.toJSONString(itemDoc);
                bulkRequest.add(request
                        .id(item.getId().toString())
                        .source(json, XContentType.JSON));
                client.bulk(bulkRequest, RequestOptions.DEFAULT);
            }
            page++;
        }
    }

    //开始连接服务端
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.128:9200")
        ));
    }

    //结束释放资源
    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
